local StickController = require("StickController")
local SpaceShipController = require("SpaceShipController")
local EquipmentController = require("EquipmentController")
local saveDataController = nil
-- 导入必要的模块
local FrameLoader = require("Utils.FrameLoader")
local PrefabFactory = require("Utils.PrefabFactory")
local MonsterManager = require("MonsterManager")
local equipmentController = nil
local Consts =require("Data.Consts")
local SaveDataController = require("SaveDataController")
local fuleCount = 100

G = {} -- 全局表
G.equpiIds = { } -- 多个Controller共享的数据

local BASIC_FULE = 70
local MONEY_PER_SECOND= 30

local cur_wave_money=0

local maxFuleCount = 50
local UINodes = require("Data.UINodes")
local ShipData = require("Data.ShipStoreData")
local seat = LuaAPI.query_unit("载具座椅18")
local region = LuaAPI.query_unit("通用触发区域17")
local startPoint = nil
local flySpeed = 30
local isFly = {}
local role = nil
local character = nil
local refucePerSecond = 15
local rankObj =nil
isFly1 = true


   LuaAPI.global_register_trigger_event({EVENT.ANY_LIFEENTITY_TRIGGER_SPACE, Enums.TriggerSpaceEventType.ENTER,
                                          region.get_id()}, function(name, actor, data)
        print("进入触发区域17")

        local character = data.event_unit
        local role = character.get_role()
        role.set_battle_shop_visible(1, true)
    end)



function UpdateUI()
    -- 初始化时需要将预览的指示器需要对所有人都默认隐藏
    for _, role in ipairs(GameAPI.get_all_valid_roles()) do
        -- isFly[role.get_roleid()] = false
        role.set_progressbar_max(UINodes["燃料进度条"],maxFuleCount)
        role.set_label_text(UINodes["获得金币文本"],tostring(cur_wave_money) )
        if (fuleCount < 1) then
            role.set_progressbar_current(UINodes["燃料进度条"], 0)
        else
            role.set_progressbar_transition(UINodes["燃料进度条"], fuleCount, 1.0)
        end

    end
end
local tree = LuaAPI.query_unit("载具座椅18")
-- LuaAPI.unit_register_trigger_event(_unit, {EVENT.SPEC_OBSTACLE_INTERACTED, }, function(event_name, actor, data)
-- 	print(data.interact_lifeentity)
-- 	print(data.interact_unit)
-- 	print(data.interact_id)
-- end)
local a =GameAPI.get_all_valid_roles()[1]
print("try 监听")
   


local itemObj = GameAPI.create_equipment(1073815583,a.get_ctrl_unit().get_position() )

LuaAPI.unit_register_trigger_event(itemObj, {EVENT.SPEC_EQUIPMENT_ENTER_CHAR_SLOT, Enums.EquipmentSlotType.EQUIPPED}, function(event_name, actor, data)
	print("xxxxxxxxxx")
    print(data.equipment)
	print(data.slot_type)
	print(data.owner)
end)



for _, role in ipairs(GameAPI.get_all_valid_roles()) do

    local u = role.get_ctrl_unit()


    
-- LuaAPI.unit_register_trigger_event(u, {EVENT.SPEC_EQUIPMENT_OBTAIN, }, function(event_name, actor, data)
-- 	print("装备获得")
--     print(data.equipment)
-- 	print(data.owner)
-- 	print(data.count)
-- end)


    LuaAPI.unit_register_trigger_event(u,
        {EVENT.SPEC_CHARACTER_SELECT_EQUIPMENT_SLOT, Enums.EquipmentSlotType.EQUIPPED, 1},
        function(event_name, actor, data)
            print("选中格子")

            local info = u.get_equipment_by_slot(Enums.EquipmentSlotType.EQUIPPED, 1)
            print("装备信息:" .. info.get_key())
            local tmp = GameAPI.create_equipment(info.get_key(), u.get_position() + math.Vector3(0, 2, 0))
            tmp.get_unit().set_lifted_enabled(true)
            u.lift_unit(tmp.get_unit())
        end)

 

end

function updateFuel()
    maxFuleCount = BASIC_FULE + getFuelExtra()
    print("更新后油量:"..maxFuleCount)
    UpdateUI ()
end

function getFuelExtra()
    
  
    local totalFuelExtra = 0
    
    -- 检查必要的全局变量是否存在
    if not saveDataController or not ShipData then
        print("错误: SaveDataController 或 ShipData 未找到")
        return 0
    end
    print(ShipData)
    print(saveDataController.equpiIds)
    -- 遍历所有装备ID
    for _, equpiId in ipairs(G.equpiIds or {}) do
        -- 从ShipData中获取装备数据
        print("eid"..equpiId)
        local equipment = ShipData[equpiId]
        if equipment and equipment.Value then
            totalFuelExtra = totalFuelExtra + equipment.Value
            print(string.format("装备ID %d 提供燃料值: %d", equpiId, equipment.Value))
        else
            print(string.format("警告: 装备ID %d 在ShipData中未找到或没有Value属性", equpiId))
        end
    end
    
    print(string.format("总燃料加成: %d", totalFuelExtra))
    return totalFuelExtra
end

LuaAPI.global_register_trigger_event({EVENT.GAME_INIT}, function()
    G.prefabFactory = PrefabFactory.new() -- 预设加载工厂类
	G.frameLoader = FrameLoader.new(1, 1) -- 分帧加载器
    G.monsterManager = MonsterManager.new() -- 怪物管理器
    -- 开始生成怪物
	G.monsterManager:startSpawn()
    local stickController = StickController.new()
    saveDataController = SaveDataController.new()
    equipmentController =EquipmentController.new()
    startPoint = LuaAPI.query_unit("简易舞台1")
    local spaceShipController = SpaceShipController.new()
    isFly1 = false
    rankObj = LuaAPI.query_unit("排行榜2")
    LuaAPI.global_register_custom_event("装备变化", function(name, unit, data)
        print("装备变化了")
        updateFuel()
    end)
    LuaAPI.global_register_custom_event("stopfly", function(name, unit, data)
        print("飞行结束获取进行:"..math.tofixed(cur_wave_money))
        isFly1=false
        role.change_attr_bonus_fixed(Consts.MoneyType.Gold, math.tofixed(cur_wave_money) )
        updateFuel()
    end)
    LuaAPI.global_register_custom_event("发射飞船", function(name, unit, data)
        print("当前unit,执行了发射哦")
        print("=== 调试 data 结构 ===")

        -- 检查 data 是否为空或无效
        if not data then
            print("data 为空")
            return
        end
        isFly1 = true
        cur_wave_money=0
        character.set_position(seat.get_position() + math.Vector3(0, 1, 0))
        fuleCount=maxFuleCount
        print("执行发射")
        spaceShipController:setCanFly(true)
    end)

    role = GameAPI.get_all_valid_roles()[1]
    -- role.set_progressbar_max(UINodes["燃料进度条"], maxFuleCount)
    -- role.set_progressbar_current(UINodes["燃料进度条"], maxFuleCount)
    -- 假设有一个角色对象和一个分数值
   
    local score = 100  -- 要设置的分数值

    -- role.set_label_text(UINodes["获得金币文本"],string(cur_wave_money) )
    print("获取存档")
    -- LuaAPI.call_delay_time(2.0, function()
    --     print("2秒后")

    --     local buildData = saveDataController:getPlayerData(role, 1001)
    --     print(buildData)
    --     for first_part in buildData:gmatch("([^;]+)") do
    --         -- 去除首尾空格
    --         first_part = first_part:gsub("^%s*(.-)%s*$", "%1")

    --         -- 第二次分割：按等号分隔
    --         local left, right = first_part:match("([^=]+)=(.+)")

    --         if left and right then
    --             createObstaclesFromPosition(right, left)
    --         end
    --     end
    -- end)

    -- local obstacles = 
    character = role.get_ctrl_unit()
    -- 定义每帧更新前的处理函数
    local function onPreTick1(_)
        if (isFly1) then
            spaceShip.set_physics_active(true)
            print("flying")
            spaceShip.set_linear_velocity(math.Vector3(0, flySpeed, 0))
        end
    end

    local triggerId = nil

    local function _timerFunc(eventName, actor, data)
        if isFly1 then
            local currentValue = fuleCount - refucePerSecond
            fuleCount = currentValue
            cur_wave_money= cur_wave_money+MONEY_PER_SECOND
            UpdateUI()
            -- 玩家回七点 飞船回起点， 燃料充满
            if (currentValue < 1) then
                spaceShipController:stopFly()
                fuleCount = maxFuleCount
                GameAPI.get_all_valid_roles()[1].get_ctrl_unit().set_position(startPoint.get_position() +
                                                                                  math.Vector3(0, 1, 0))
            end
        end

    end
    -- 将_timerFunc注册到全局触发器中
    triggerId = LuaAPI.global_register_trigger_event({EVENT.REPEAT_TIMEOUT, 1.0}, _timerFunc)
    local function onPreTick()
        stickController:update()
        spaceShipController:update()
    end

    LuaAPI.set_tick_handler(onPreTick, nil)
end)

-- 定义生成障碍物的函数
-- @param positionData string 格式为"x,y,z"的位置字符串，多个位置用分号隔开
-- @param obstaclePrefabID integer 障碍物的预设ID
function createObstaclesFromPosition(positionData, obstaclePrefabID)
    -- 分割多个位置数据
    -- local positionList = {}
    -- for posStr in string.gmatch(positionData, "[^;]+") do
    --     table.insert(positionList, posStr)
    -- end

    -- 遍历所有位置创建障碍物
    local createdObstacles = {}
    -- for _, posStr in ipairs(positionList) do
    -- 解析x,y,z坐标
    local x, y, z = string.match(positionData, "([^,]+),([^,]+),([^,]+)")
    x = math.tofixed(x)
    y = math.tofixed(y)
    z = math.tofixed(z)

    -- 创建障碍物
    local position = math.Vector3(x, y, z)
    local rotation = math.Quaternion(0, 0, 0) -- 默认无旋转
    local scale = math.Vector3(1, 1, 1) -- 默认无缩放
-- obstaclePrefabID=1073774658


-- position= math.Vector3(16.420061069,1.9900000117,8.4805982493)
    local obstacle = GameAPI.create_equipment(math.tointeger(obstaclePrefabID) , position)
  
    table.insert(createdObstacles, obstacle)
    -- end

    return createdObstacles
end

-- local function onPostTick()
-- end
-- LuaAPI.set_tick_handler(onPreTick1, onPostTick)
